publicbooleansendBroadcast(Intent intent){ synchronized (mReceivers) { //【1】解析 intent 的相关属性! final String action = intent.getAction(); final String type = intent.resolveTypeIfNeeded( mAppContext.getContentResolver()); final Uri data = intent.getData(); final String scheme = intent.getScheme(); final Set<String> categories = intent.getCategories();
finalboolean debug = DEBUG || ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); if (debug) Log.v( TAG, "Resolving type " + type + " scheme " + scheme + " of intent " + intent); //【2】从 mActions 映射表中找到能够处理该 intent 的接收者列表! ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction()); if (entries != null) { if (debug) Log.v(TAG, "Action list: " + entries);
ArrayList<ReceiverRecord> receivers = null; // 保存目标 receiver 实例; for (int i=0; i<entries.size(); i++) { //【2.1】处理每一个 ReceiverRecord 实例; ReceiverRecord receiver = entries.get(i); if (debug) Log.v(TAG, "Matching against filter " + receiver.filter); //【2.2】如果 receiver.broadcasting 为 true,说明目标 receiver 已经添加到目标集合中了; if (receiver.broadcasting) { if (debug) { Log.v(TAG, " Filter's target already added"); } continue; } //【2.3】匹配 receiver! int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager"); //【2.4】匹配成功,将目标 receiver 加入到目标列表中! if (match >= 0) { if (debug) Log.v(TAG, " Filter matched! match=0x" + Integer.toHexString(match)); if (receivers == null) { receivers = new ArrayList<ReceiverRecord>(); } receivers.add(receiver); receiver.broadcasting = true; // 设置 broadcasting 为 true! } else { if (debug) { String reason; switch (match) { case IntentFilter.NO_MATCH_ACTION: reason = "action"; break; case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break; case IntentFilter.NO_MATCH_DATA: reason = "data"; break; case IntentFilter.NO_MATCH_TYPE: reason = "type"; break; default: reason = "unknown reason"; break; } Log.v(TAG, " Filter did not match: " + reason); } } } //【3】收集完所有匹配的 receiver,开始发送广播! if (receivers != null) { //【3.1】将所有 receiver 的 broadcasting 置为 false; for (int i=0; i<receivers.size(); i++) { receivers.get(i).broadcasting = false; } //【2.4.1】创建 BroadcastRecord 实例,将其添加到 mPendingBroadcasts 列表中! mPendingBroadcasts.add(new BroadcastRecord(intent, receivers)); if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) { //【3.1】发送 MSG_EXEC_PENDING_BROADCASTS,处理广播! mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS); } returntrue; } } } returnfalse; }
在 LocalBroadcastManager 还有如下的一个 list 表:
1 2 3
// 保存所有等待发送的 broadcast! privatefinal ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<BroadcastRecord>();